package com.sinopec.uhf.uhfhelp;

import android.util.Log;
import android.widget.Toast;

import com.naz.serial.port.ModuleManager;
import com.payne.connect.port.SerialPortHandle;
import com.payne.reader.bean.config.AntennaCount;
import com.payne.reader.bean.config.MemBank;
import com.payne.reader.bean.send.ReadConfig;
import com.sinopec.uhf.R;
import com.sinopec.uhf.bean.OperationTagBean;
import com.sinopec.uhf.model.BeeperHelper;
import com.sinopec.uhf.model.ReaderHelper;
import com.sinopec.uhf.model.RxBleHelper;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建人：吴冬冬<br/>
 * 创建时间：2021/8/10 11:29 <br/>
 */
public class UhfHelp {
    private UhfHelp() {
    }

    public static void applicationOnCreate() {
        PreferenceUtil.init(AppGlobals.getApplication());
        BeeperHelper.init(AppGlobals.getApplication());
    }

    public static void applicationOnTerminate() {
        ModuleManager.newInstance().setUHFStatus(false);
        ReaderHelper.getReader().disconnect();
        RxBleHelper.getInstance().release();
        ModuleManager.newInstance().release();
    }
    /////////////////////////////////////////////////////////////

    //初始化连接
    public static void initConnection() {
        ModuleManager.newInstance().setUHFStatus(true);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ModuleManager.newInstance().setUHFStatus(false);
        int baud = 115200;
        String devicePath = "/dev/ttymxc2";
        SerialPortHandle handle = new SerialPortHandle(devicePath, baud);
        boolean connectSuccess = ReaderHelper.getReader().connect(handle);
        if (connectSuccess) {
            if (!ModuleManager.newInstance().setUHFStatus(true)) {
                Toast.makeText(AppGlobals.getApplication(), R.string.power_on_failed, Toast.LENGTH_SHORT).show();
            } else {
                //App.setLinkType(LinkType.LINK_TYPE_SERIAL_PORT);
            }
        } else {
            Toast.makeText(AppGlobals.getApplication(), R.string.serial_connect_failed, Toast.LENGTH_SHORT).show();
        }
        ReaderHelper.getReader().switchAntennaCount(AntennaCount.EIGHT_CHANNELS);
    }

    public static void closeConnection() {
        ReaderHelper.getReader().disconnect();
        ModuleManager.newInstance().setUHFStatus(false);
    }

    //全局监听
//    public static void addAllCallback() {
//        long cmdTimeout = Hawk.get(Key.CMD_TIMEOUT, 2000L);
//        ReaderHelper.getReader().setCmdTimeout(cmdTimeout);
//        ReaderHelper.getReader().setOriginalDataCallback(
//                bytes -> {
//                    //Log.e("gpenghui", "  发送: " + ArrayUtils.bytesToHexString(bytes, 0, bytes.length));
//                },
//                bytes -> {
//                    //Log.e("gpenghui", "--接收: " + ArrayUtils.bytesToHexString(bytes, 0, bytes.length));
//                });
//        ReaderHelper.getReader().setCommandStatusCallback(cmdStatus -> {
//            if (cmdStatus.getStatus() == ResultCode.REQUEST_TIMEOUT) {
//                return;
//            }
//            /*if (logView.getVisibility() == View.VISIBLE) {
//                String status = StringFormat.formatTempLabel2(cmdStatus.getCmd(), cmdStatus.getStatus());
//                if (cmdStatus.getCmd() == Cmd.SET_WORK_ANTENNA) {
//                    status += getString(R.string.stitch_ant) + (ReaderHelper.getReader().getCacheWorkAntenna() + 1);
//                }
//                if (cmdStatus.getStatus() == ResultCode.ANTENNA_MISSING_ERROR) {
//                    status += getString(R.string.stitch_ant) + (cmdStatus.getAntId() + 1);
//                }
//                LogBean bean = new LogBean(status, cmdStatus.getStatus() == ResultCode.SUCCESS);
//                runOnUiThread(() -> logView.addData(bean));
//            }*/
//        });
//    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public interface Callback {
        void callback(OperationTagBean bean);
    }

    private static final CompositeDisposable sCd = new CompositeDisposable();
    private static int sBtAntNum = -1;
    private static final Scheduler FROM_SCHEDULER = Schedulers.from(Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(@NotNull Runnable r) {
            return new Thread(r, "uhf-thread");
        }
    }), true);

    public static void readTags(boolean isStart, Callback callback) {
        if (isStart) {
            sCd.add(Observable.
                    interval(10, 110, TimeUnit.MILLISECONDS)
                    .observeOn(FROM_SCHEDULER)
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            //读标签
                            MemBank memBank = MemBank.valueOf((byte) 3);
                            byte startAddress = (byte) Integer.parseInt("00");
                            int readLen = 6;
                            ReadConfig config = new ReadConfig.Builder()
                                    .setPasswords("00000000")
                                    .setMemBank(memBank)
                                    .setWordStartAddress(startAddress)
                                    .setWordLength((byte) readLen)
                                    .build();
                            ReaderHelper.getReader().readTag(
                                    config,
                                    operationTag -> {
                                        //123============== 使用str data为数据展示
                                        //1、判断user区 数据是否 满足规格，满足直接使用user区数据
                                        //2、不满足，使用epc数据
                                        //Log.e("123===", "============" + StringUtils.validationRfidRule(operationTag.getStrData()));
                                        //Log.e("123===", "获取到数据data：" + operationTag.getStrData());
                                        //Log.e("123===", "获取到数据epc：" + operationTag.getStrEpc());
                                        if (!StringUtils.validationRfidRule(operationTag.getStrData())) {
                                            Log.e("123===", "=======================11111111111============");
                                            //123===添加 String截取后12位
                                            if (operationTag.getStrEpc().length() <= 17) {
                                                //Log.e("123===", "=======================22222222222============");
                                                operationTag.setStrData(operationTag.getStrEpc());
                                            } else {
                                                //Log.e("123===", "=======================33333333333============");
                                                operationTag.setStrData(StringUtils.getScanCode(operationTag.getStrData()));
                                            }

                                           // Log.e("123===", "111111111111获取到数据data：" + operationTag.getStrData());
                                            if (!StringUtils.validationRfidRule(operationTag.getStrData())) {
                                                //不满足规则，return
                                                //Log.e("123===", "不满足规则，return===================================");
                                                return;
                                            }
                                        }
                                        Log.e("123===", "=======================44444444444============");
                                        OperationTagBean bean = new OperationTagBean(operationTag);
                                        //Log.e("123===", "返回数据：" + bean.getData());
                                        callback.callback(bean);
                                        //StringFormat.format(operationTag.getCmd(), ResultCode.SUCCESS););
                                    }, failure -> {
                                        //String failureStr = StringFormat.format(failure.getCmd(), failure.getErrorCode());
                                        //Log.e("123===", "failurefailurefailurefailure===================================" + failureStr);
                                    });
                        }
                    }));
            sCd.add(Observable.
                    interval(0, 100, TimeUnit.MILLISECONDS)
                    .observeOn(FROM_SCHEDULER)
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (sBtAntNum == 0) {
                                sBtAntNum = 1;
                            } else if (sBtAntNum == 1) {
                                sBtAntNum = 2;
                            } else if (sBtAntNum == 2) {
                                sBtAntNum = 3;
                            } else if (sBtAntNum == 3) {
                                sBtAntNum = 4;
                            } else if (sBtAntNum == 4) {
                                sBtAntNum = 5;
                            } else {
                                sBtAntNum = 0;
                            }
                            ReaderHelper.getReader().setWorkAntenna((byte) sBtAntNum,
                                    success -> {
                                        //Log.e("123===", "天线切换成功：" + sBtAntNum);
                                    },
                                    failure -> {
                                        //String failureStr = StringFormat.format(failure.getCmd(), failure.getErrorCode());
                                        //Log.e("123===", failureStr + "   天线切换失败：" + sBtAntNum);
                                    });
                        }
                    }));
        } else {
            sCd.clear();
        }
    }
}
